<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>我的病历</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <script src="/js/jquery.min.js"></script>
    <script src="/js/bootstrap.bundle.min.js"></script>
    <style>
        body { margin: 0; padding: 0; background: #f5f6fa; display: flex; min-height: 100vh; }
        .main-wrapper { display: flex; width: 100%; }
        .sidebar {
            width: 240px;
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            padding: 0;
            box-shadow: 2px 0 8px rgba(0,0,0,0.07);
            min-height: 100vh;
            color: #fff;
            display: flex;
            flex-direction: column;
            align-items: stretch;
        }
        .sidebar h3 {
            color: #fff;
            font-weight: bold;
            text-align: center;
            padding: 32px 0 16px 0;
            letter-spacing: 2px;
            font-size: 1.3rem;
            margin-bottom: 0;
        }
        .sidebar ul {
            list-style: none;
            padding: 0 0 32px 0;
            margin: 0;
            flex: 1;
        }
        .sidebar ul li {
            margin: 0;
        }
        .sidebar ul li a {
            display: flex;
            align-items: center;
            padding: 14px 32px;
            color: #e3e6f0;
            text-decoration: none;
            font-size: 1.08rem;
            border-left: 4px solid transparent;
            transition: background 0.2s, color 0.2s, border-color 0.2s;
            border-radius: 0 24px 24px 0;
            margin-bottom: 2px;
        }
        .sidebar ul li a:hover,
        .sidebar ul li a.active {
            background: rgba(255,255,255,0.12);
            color: #fff;
            border-left: 4px solid #f6c23e;
            font-weight: bold;
        }
        .sidebar ul li a .icon {
            margin-right: 10px;
            font-size: 1.2em;
        }
        .main-content { flex-grow: 1; padding: 20px; background-color: #f5f6fa; }
        .info-card { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
    </style>
</head>
<body>
<div class="main-wrapper">
    <div class="sidebar">
        <h3>医院病例管理系统</h3>
        <ul>
            <li><a href="/personalInfo">个人信息</a></li>
            <li><a href="/myMedicalRecords" class="active">我的病历</a></li>
            <li><a href="/registerAppointment">在线挂号</a></li>
        </ul>
    </div>
    <div class="main-content">
        <div class="info-card">
            <h2>我的病历</h2>
            <div class="mb-3">
                <input type="text" class="form-control" id="searchInput" placeholder="搜索病历...">
            </div>
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>挂号ID</th>
                        <th>医生姓名</th>
                        <th>诊断结果</th>
                        <th>日期</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="medicalRecordsTableBody">
                    <!-- 病历数据将在这里加载 -->
                </tbody>
            </table>
            <div id="medicalRecordsLoading" class="text-center" style="display: none;">加载中...</div>
            <div id="medicalRecordsError" class="alert alert-danger" style="display: none;">加载失败</div>
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center" id="pagination">
                    <!-- 分页控件将在这里动态加载 -->
                </ul>
            </nav>
        </div>
    </div>
</div>
<script>
$(function(){
    let allRecords = [];

    function renderTable(records) {
        const $tbody = $('#medicalRecordsTableBody');
        $tbody.empty();
        if (records.length === 0) {
            $tbody.append('<tr><td colspan="5" class="text-center">暂无病历记录</td></tr>');
            return;
        }
        records.forEach(record => {
            const $row = $('<tr>');
            $row.append($('<td>').text(record.registerId));
            $row.append($('<td>').text(record.doctorUsername || '-'));
            $row.append($('<td>').text(record.diagnosis || '-'));
            $row.append($('<td>').text( new Date( record.registerTime).toLocaleString()));
            const $viewButton = $('<button>')
                .addClass('btn btn-sm btn-info view-medical-record-btn me-2')
                .text('查看详情')
                .attr('data-id', record.id);
            const $actionsCell = $('<td>').append($viewButton);
            $row.append($actionsCell);
            $tbody.append($row);
        });
    }

    function loadMedicalRecords() {
        $('#medicalRecordsLoading').show();
        $('#medicalRecordsError').hide();
        $('#medicalRecordsTableBody').empty();
        $.ajax({
            url: '/medical/user/list',
            type: 'GET',
            success: function(res) {
                $('#medicalRecordsLoading').hide();
                if (res.code === 0 && res.data) {
                    allRecords = res.data;
                    renderTable(allRecords);
                } else {
                    $('#medicalRecordsError').text(res.message || '获取病历列表失败').show();
                }
            },
            error: function() {
                $('#medicalRecordsLoading').hide();
                $('#medicalRecordsError').text('请求失败，请稍后重试').show();
            }
        });
    }

    $('#searchInput').on('input', function(){
        const keyword = $(this).val().trim().toLowerCase();
        const filtered = allRecords.filter(record =>
            (record.diagnosis && record.diagnosis.toLowerCase().includes(keyword)) ||
            (record.doctorUsername && record.doctorUsername.toLowerCase().includes(keyword)) ||
            (record.registerId && String(record.registerId).includes(keyword))
        );
        renderTable(filtered);
    });

    $('#medicalRecordsTableBody').on('click', '.view-medical-record-btn', function(){
        const recordId = $(this).data('id');
        if (!recordId) return;
        $.ajax({
            url: '/medical/user/' + recordId,
            type: 'GET',
            success: function(res) {
                if (res.code === 0 && res.data) {
                    const record = res.data;
                    console.log('Record:', record);
                    let html = '';
                    html += '<strong>挂号ID：</strong>' + (record.registerId || '-') + '<br>';
                    html += '<strong>医生姓名：</strong>' + (record.doctorUsername || '-') + '<br>';
                    html += '<strong>挂号时间：</strong>' + (new Date(record.registerTime).toLocaleString() || '-') + '<br>';
                    html += '<strong>主诉：</strong>' + (record.readme || '-') + '<br>';
                    html += '<strong>现病史：</strong>' + (record.present || '-') + '<br>';
                    html += '<strong>现病治疗情况：</strong>' + (record.presentTreat || '-') + '<br>';
                    html += '<strong>既往史：</strong>' + (record.history || '-') + '<br>';
                    html += '<strong>过敏史：</strong>' + (record.allergy || '-') + '<br>';
                    html += '<strong>体格检查：</strong>' + (record.physique || '-') + '<br>';
                    html += '<strong>检查/检验建议：</strong>' + (record.proposal || '-') + '<br>';
                    html += '<strong>注意事项：</strong>' + (record.careful || '-') + '<br>';
                    html += '<strong>诊断结果：</strong>' + (record.diagnosis || '-') + '<br>';
                    html += '<strong>处理意见：</strong>' + (record.cure || '-') + '<br>';

                    showDetailModal('病历详情', html);
                } else {
                    alert(res.message || '获取病历详情失败');
                }
            },
            error: function() {
                alert('请求失败，请稍后重试');
            }
        });
    });

    function showDetailModal(title, html) {
        let $modal = $('#medicalRecordDetailModal');
        if ($modal.length === 0) {
            $modal = $(`
                <div class="modal fade" id="medicalRecordDetailModal" tabindex="-1" aria-labelledby="medicalRecordDetailModalLabel" aria-hidden="true">
                  <div class="modal-dialog">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title" id="medicalRecordDetailModalLabel"></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                      </div>
                      <div class="modal-body"></div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" id="downloadMedicalRecordBtn">下载/打印</button>
                      </div>
                    </div>
                  </div>
                </div>
            `);
            $('body').append($modal);
        }
        $modal.find('.modal-title').text(title);
        $modal.find('.modal-body').html(html);

        // 绑定下载/打印事件
        $modal.find('#downloadMedicalRecordBtn').off('click').on('click', function() {
            printMedicalRecord(title, html);
        });

        const modal = new bootstrap.Modal($modal[0]);
        modal.show();
    }

    function printMedicalRecord(title, html) {
        const printWindow = window.open('', '', 'height=600,width=800');
        printWindow.document.write('<html><head><title>' + title + '</title>');
        printWindow.document.write('<link rel="stylesheet" href="/css/bootstrap.min.css">');
        printWindow.document.write('</head><body>');
        printWindow.document.write('<h2 style="text-align:center;">' + title + '</h2>');
        printWindow.document.write('<div>' + html + '</div>');
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.focus();
        printWindow.print();
    }

    loadMedicalRecords();
});
</script>
</body>
</html> 